<template>
  <div class="m-auto max-w-700 min-w-445 f-c-c rounded-8 bg-#fff bg-cover p-12 card-shadow auto-bg">
    <div class="hidden w-380 px-20 py-35 md:block">
      <img class="w-full" src="../images/ai2.png" alt="login_banner" />
    </div>
    <div class="w-320 flex-col px-20 py-32">
      <div class="text-26 whitespace-nowrap">{{ appStore.info.title }}</div>
      <div class="text-red-600 h-32 lh-32"></div>

      <a-form :model="loginInfo" ref="formEl">
        <a-form-item :rules="[{ required: true, message: '' }]" name="username">
          <a-input placeholder="请输入用户名" v-model:value="loginInfo.username">
            <template #prefix>
              <UserOutlined class="text-gray"></UserOutlined>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item :rules="[{ required: true, message: '' }]" name="password">
          <a-input-password placeholder="请输入密码" v-model:value="loginInfo.password">
            <template #prefix>
              <LockOutlined class="text-gray"></LockOutlined>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item :rules="[{ required: true, message: '' }]" name="code">
          <a-row :gutter="15">
            <a-col :span="16">
              <a-input allow-clear placeholder="请输入验证码" v-model:value="loginInfo.code">
                <template #prefix>
                  <SafetyOutlined class="text-gray"></SafetyOutlined>
                </template>
              </a-input>
            </a-col>
            <a-col :span="8">
              <img class="cursor-pointer rounded-4" @click="getCaptcha()" :src="captcha" alt="" />
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>

      <a-space direction="vertical" size="large" class="w-full">
        <a-checkbox v-model:checked="isRemember">记住密码</a-checkbox>
        <a-button type="primary" size="large" class="w-full" @click="onLogin" :loading="loading">
          登录
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons-vue'
import { isEmpty, throttle } from 'xe-utils'
import { ref } from 'vue'
import userApi, { LoginDto, LoginRes } from '@/api/user.ts'
import { useStorage } from '@vueuse/core'
import { message as Message } from 'ant-design-vue'
import useLoading from '@/hooks/loading.ts'
import { lStorage } from '@/utils/storage'
import { useAuthStore, useAppStore } from '@/store'

const formEl = ref()
const isRemember = useStorage('isRemember', true)
const { loading, setLoading } = useLoading()
const authStore = useAuthStore()
const appStore = useAppStore()

const route = useRoute()
const router = useRouter()

const loginInfo = ref<LoginDto>({
  password: null,
  username: null,
  code: null,
})

const captcha = ref('/api/captcha/80/32?t=' + new Date().valueOf())
const getCaptcha = () => {
  throttle(() => {
    captcha.value = '/api/captcha/80/32?t=' + new Date().valueOf()
  }, 500)()
}

const localLoginInfo = lStorage.get('loginInfo')
if (localLoginInfo) {
  loginInfo.value.username = localLoginInfo.username || ''
  loginInfo.value.password = localLoginInfo.password || ''
}

function onLogin() {
  setLoading(true)
  formEl.value
    .validate()
    .then(() => {
      userApi
        .login(loginInfo.value)
        .then((rep) => {
          const { username, password } = loginInfo.value
          if (isRemember.value) {
            lStorage.set('loginInfo', { username, password })
          } else {
            lStorage.remove('loginInfo')
          }
          onLoginSuccess(rep.data)
          setTimeout(() => {
            setLoading(false)
          }, 1000)
        })
        .catch(() => {
          setLoading(false)
        })
    })
    .catch(() => {
      const { username, password, code } = loginInfo.value
      if (!username || !password) return Message.error('请输入用户名和密码')
      if (isEmpty(code)) return Message.error('请输入验证码')
      setLoading(false)
    })
}

function onLoginSuccess(res: LoginRes) {
  authStore.setToken(res)
  Message.loading({
    content: '登录中...',
    key: 'login',
  })
  try {
    Message.success('登录成功')
    if (route.query.redirect) {
      const path = route.query.redirect
      delete route.query.redirect

      router.push({ path: path as string, query: route.query })
    } else {
      router.push('/')
    }
    Message.destroy('login')
  } catch (error) {
    console.error(error)
    Message.destroy('login')
  }
}
</script>
